﻿using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Text;

namespace VSM
{
    public partial class CustomerProfileEdit : System.Web.UI.Page
    {
        private static DataTable dtHeader;
        private static DataTable dtContactPerson;
        private static DataTable dtAddress;
        
        //private string TblHeaderName = "OCRD";
        //private string TblAddress = "CRD1";
        //private string TblContact = "OCPR";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session[Utils.AppConstants.ID_User] == null
                || Session[Utils.AppConstants.Password] == null
                || Session[Utils.AppConstants.ID_Dealer] == null)
            {
                Response.Redirect("../../Login.aspx");
            }

            if (!IsPostBack)
            {
                string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                Session["GeneralFunctions"] = GF;
                LoadCarType(dbType); // Load & binding CarType ddl.
                LoadSaleMan(dbType);

                if (Request.QueryString["id"] != null && Request.QueryString["id"].Length > 0)
                {
                    hdnCustomerCode.Value = Request.QueryString["id"];
                    btnUpdate.Text = "Update Customer";

                }
                else // Add new Customer
                {
                    hdnCustomerCode.Value = string.Empty;
                    txtCustomerCode.Text = "Auto.";
                    btnUpdate.Text = "Add Customer";
                }
                   
                //if (string.Compare("VSM", (string)Session[Utils.AppConstants.ID_Dealer]) == 0) // VSM site
                {
                    LoadData(dbType, Request.QueryString["id"].ToString());
                    LoadDetails(dbType, this.txtCustomerCode.Text.Trim(), "A");
                    LoadDetails(dbType, this.txtCustomerCode.Text.Trim(), "B");
                    LoadDetails(dbType, this.txtCustomerCode.Text.Trim(), "C");
                    LoadDetails(dbType, this.txtCustomerCode.Text.Trim(), "D");
                    LoadDetails(dbType, this.txtCustomerCode.Text.Trim(), "E");
                    LoadDetails(dbType, this.txtCustomerCode.Text.Trim(), "F");
                }
                //else // Dealer Site
                //{
                //    LoadData(Utils.AppConstants.DEALER, Request.QueryString["id"].ToString());
                //    LoadDetails(dbType, this.txtCustomerCode.Text.Trim(), "A");
                //    LoadDetails(dbType, this.txtCustomerCode.Text.Trim(), "B");
                //    LoadDetails(dbType, this.txtCustomerCode.Text.Trim(), "C");
                // 
                if (ddl_CustomerType.SelectedValue.Equals("L"))
                    lblNotification.Visible = false; //to hide
                else // show notification when it's a customer.
                    lblNotification.Visible = true; //to show
                SetInvisibleFields(ddlBPType.SelectedValue);
            }
        }

        private void LoadDetails(string dbType, string CardCode, string Type)
        {
            GeneralFunctions GF = (GeneralFunctions)Session["GeneralFunctions"];
            DataTable dtDetails = GF.GetCustomerDetails(dbType, CardCode, Type);
            dtDetails.TableName = "tbl_" + Type + "CRD10";
            if(dtDetails != null) BindDataDetails(dtDetails, Type);
        }

        private void BindDataDetails(DataTable dtDetails, string Type)
        {
            switch (Type)
            {
                case "A":
                    Session["ACRD10Table"] = dtDetails;
                    grvA.DataSource = dtDetails;
                    grvA.DataBind();
                    break;
                case "B":
                    Session["BCRD10Table"] = dtDetails;
                    grvB.DataSource = dtDetails;
                    grvB.DataBind();
                    break;
                case "C":
                    Session["CCRD10Table"] = dtDetails;
                    grvC.DataSource = dtDetails;
                    grvC.DataBind();
                    break;

                case "D":
                    Session["DCRD10Table"] = dtDetails;
                    if (dtDetails != null && dtDetails.Rows.Count > 0)
                    {
                        ddlCarType.SelectedValue = dtDetails.Rows[0]["CarType"].ToString();
                        txtPaymentMethod.Text = dtDetails.Rows[0]["PaymentMethod"].ToString();
                        txtBankName.Text = dtDetails.Rows[0]["BankName"].ToString();
                    }
                    else
                    {
                        ddlCarType.SelectedValue = 
                        txtPaymentMethod.Text = 
                        txtBankName.Text = string.Empty;
                    }
                    break;

                case "E":
                    Session["ECRD10Table"] = dtDetails;
                    grvE.DataSource = dtDetails;
                    grvE.DataBind();
                    break;
                case "F":
                    Session["FCRD10Table"] = dtDetails;
                    grvF.DataSource = dtDetails;
                    grvF.DataBind();
                    break;
            }
        }

        private void LoadCarType(string dbType)
        {
            try
            {
                GeneralFunctions GF = (GeneralFunctions)Session["GeneralFunctions"];
                DataTable dtProduct = GF.GetMasterListBySqlCommand(dbType, "SELECT distinct Code, Name FROM [dbo].[@PRODUCTSALES]");
                ddlCarType.DataSource = dtProduct;
                ddlCarType.DataValueField = "Code";
                ddlCarType.DataTextField = "Name";
                ddlCarType.DataBind();
                ddlCarType.Items.Insert(0, string.Empty);
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
                lblError.Visible = true;
            }
        }

        private void LoadSaleMan(string dbType)
        {
            GeneralFunctions GF = (GeneralFunctions)Session["GeneralFunctions"];
            DataTable dtSaleMan = GF.GetMasterListBySqlCommand(dbType, " select SlpCode, SlpName from OSLP where ( U_Code = '" + Session[Utils.AppConstants.ID_Dealer].ToString() + "' or SlpCode = -1 )");

            if (dtSaleMan != null)
            {
                ddlSaleMan.DataSource = dtSaleMan;
                ddlSaleMan.DataValueField = "SlpCode";
                ddlSaleMan.DataTextField = "SlpName";
                ddlSaleMan.DataBind();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void LoadData(string dbType, string CardCode)
        {
            Transaction trx = new Transaction();
            DataSet ds = trx.GetMarketingDocument_ReturnDS( ConvertDocType.Get2String(DocType.BUSINESS_PARTNER), CardCode, dbType);
            dtHeader = ds.Tables[0];
            dtAddress = ds.Tables[1];
            dtContactPerson = trx.GetMarketingDocument_ReturnDS(ConvertDocType.Get2String(DocType.CONTACT_PERSON), CardCode, dbType).Tables[0];

            BindData(dtHeader);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {
            if (tblData.Rows.Count > 0)
            {
                DataRow dr = tblData.Rows[0];
                txtCustomerCode.Text = dr["CardCode"].ToString();
                txtCustomerName.Text = dr["CardName"].ToString();
                txtAddress.Text = dr["Address"].ToString();
                txtTaxCode.Text = dr["LicTradNum"].ToString();
                txtHomeTel.Text = dr["Phone1"].ToString();
                txtOfficeTel.Text = dr["Phone2"].ToString();
                txtMobiphone.Text = dr["Cellular"].ToString();
                txtE_Mail.Text = dr["E_mail"].ToString();
                txtFax.Text = dr["Fax"].ToString();
                // User define field
                txtIDCard.Text = dr["U_IDCard"].ToString();
                txtAge.Text = dr["U_Age"].ToString();
                if(rblGender.Items.FindByValue(dr["U_Gender"].ToString()) != null)
                    rblGender.Items.FindByValue(dr["U_Gender"].ToString()).Selected = true;

                if (ddl_Marital.Items.FindByValue(dr["U_MarialStatus"].ToString()) != null)
                    ddl_Marital.Items.FindByValue(dr["U_MarialStatus"].ToString()).Selected = true;

                txtIncome.Text = dr["U_Income"].ToString();
                txtMembersNo.Text = dr["U_MembersNumber"].ToString();
                txtMMCOwnedQty.Text = dr["U_MMCownedNumber"].ToString();
                txtMMCOwnedName.Text = dr["U_MMCOwnedType"].ToString();
                txtOtherCarOwnedQty.Text = dr["U_OtherCar"].ToString();
                txtOtherCarOwnedName.Text = dr["U_OtherCarOwned"].ToString();
                txtPurposePrivate.Text = dr["U_PurposePrivate"].ToString();
                txtPurposeCompany.Text = dr["U_PurposeCompany"].ToString();
                txtRemark.Text = dr["Free_Text"].ToString();
                //
                txtCntctPrsn.Text = dr["U_ContactPerson"].ToString();
                ddlBPType.SelectedValue = dr["CmpPrivate"].ToString();
                ddl_CustomerType.SelectedValue = dr["CardType"].ToString();
                ddlCustomerStatus.SelectedValue = dr["U_CustomerStatus"].ToString();
                ddlSaleMan.SelectedValue = dr["SlpCode"].ToString();
                //
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString().Equals(Utils.AppConstants.VSM) ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString()); 
                txtProvinceCode.Text = dr["U_ProvinceCode"].ToString();
                txtProvinceName.Text = GF.GetSingleValue(dbType, " select Name from [@PROVINCECODE] where Code = " + dr["U_ProvinceCode"].ToString(), "Name");
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "SelectProvince":
                            this.lblError.Visible = false;
                            this.txtProvinceCode.Text = Session["ChosenCode"] != null ? Session["ChosenCode"].ToString() : string.Empty;
                            this.txtProvinceName.Text = Session["ChosenName"] != null ? Session["ChosenName"].ToString() : string.Empty;
                            Session["ChosenCode"] = 
                            Session["ChosenName"] =
                            Session["ChosenProvince"] = null;
                            break;

                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString().Equals(Utils.AppConstants.VSM) ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                // Check Valid Data
                string lsMessageBuilder = string.Empty;
                if(ddl_CustomerType.SelectedValue.Equals("C")) lsMessageBuilder = CheckValidData();
                if (lsMessageBuilder.Length > 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('" + lsMessageBuilder + "');", true);
                    return;
                }

                //if (ddlBPType.SelectedValue.Equals("I") && string.IsNullOrEmpty(txtIDCard.Text.Trim()))
                //{
                //    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing ID. Card.','');", true);
                //    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                //    return;
                //}

                //if (ddlBPType.SelectedValue.Equals("C") && string.IsNullOrEmpty(txtTaxCode.Text.Trim()))
                //{
                //    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Tax Code.','');", true);
                //    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                //    return;
                //}

                String requestXML = CollectData();
                DataSet dsDetails = CollectDataDetails();

                Transaction ts = new Transaction();
                DataSet ds = ts.CreateUpdateCustomer(dbType, requestXML, !string.IsNullOrEmpty(hdnCustomerCode.Value), txtCustomerCode.Text, dsDetails);

                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    Session["requestXML"] = requestXML;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }

        private string CheckValidData()
        {
            string MessageBuilder = string.Empty;
            string newLine = "\\n", comma = "; ", Prefix_Msg = "You must be input data for all fields below: \\n";

            try
            {
                if (string.IsNullOrEmpty(txtCustomerName.Text.Trim())) MessageBuilder += lblCustomerName.Text + newLine;
                if (string.IsNullOrEmpty(txtAddress.Text.Trim())) MessageBuilder += lblAddress.Text + comma;
                if (string.IsNullOrEmpty(txtCntctPrsn.Text.Trim())) MessageBuilder += lblContactPerson.Text + comma;
                if (string.IsNullOrEmpty(txtProvinceCode.Text.Trim())) MessageBuilder += lblProvince.Text + newLine;

                // BP. Type
                if (ddlBPType.SelectedValue.Equals("I"))
                {
                    if (string.IsNullOrEmpty(txtIncome.Text.Trim())) MessageBuilder += lblIncome.Text + comma;
                    if (string.IsNullOrEmpty(txtAge.Text.Trim())) MessageBuilder += lblAge.Text + comma;
                    if (string.IsNullOrEmpty(txtIDCard.Text.Trim())) MessageBuilder += txtIDCard.Text + newLine;
                }
                else if (ddlBPType.SelectedValue.Equals("C"))
                {
                    if (string.IsNullOrEmpty(txtFax.Text.Trim())) MessageBuilder += lblFax.Text + comma;
                    if (string.IsNullOrEmpty(txtAge.Text.Trim())) MessageBuilder += lblYoF.Text + comma;
                    if (string.IsNullOrEmpty(txtTaxCode.Text.Trim())) MessageBuilder += lblTaxCode.Text + newLine;
                }

                // 
                if (string.IsNullOrEmpty(txtE_Mail.Text.Trim())) MessageBuilder += lblEmail.Text + comma;
                if (string.IsNullOrEmpty(txtMembersNo.Text.Trim())) MessageBuilder += lblMemNumber.Text + comma;
                if (string.IsNullOrEmpty(txtHomeTel.Text.Trim()) && string.IsNullOrEmpty(txtOfficeTel.Text.Trim()) && string.IsNullOrEmpty(txtMobiphone.Text.Trim())) MessageBuilder += lblTelephone.Text + newLine;

                if (string.IsNullOrEmpty(txtMMCOwnedQty.Text.Trim()) || string.IsNullOrEmpty(txtMMCOwnedName.Text.Trim())) MessageBuilder += lblMitsOwned.Text + comma;
                if (string.IsNullOrEmpty(txtOtherCarOwnedQty.Text.Trim()) || string.IsNullOrEmpty(txtOtherCarOwnedName.Text.Trim())) MessageBuilder += lblOtherCarsOwned.Text + comma;
                if (string.IsNullOrEmpty(txtPurposePrivate.Text.Trim())) MessageBuilder += lblPurposeOfUsed.Text + " " + lblPrivate.Text.ToLower() + newLine;

                if (string.IsNullOrEmpty(txtPurposeCompany.Text.Trim())) MessageBuilder += lblPurposeOfUsed.Text + " " + lblCompany.Text.ToLower() + comma;
                if (string.IsNullOrEmpty(txtRemark.Text.Trim())) MessageBuilder += lblRemark.Text + comma;

                // Knowledge Mitsubishi By tabpage ...
                bool lbRequired = true;
                DataTable tblACRD10 = (DataTable)Session["ACRD10Table"];
                if (tblACRD10 != null)
                {
                    foreach (DataRow dr in tblACRD10.Rows)
                    {
                        if (dr["Selected"].ToString().Equals("True"))
                        {
                            lbRequired = false;
                            break;
                        }
                    }
                    if (lbRequired) MessageBuilder += "Knowledge Mitsubishi By" + comma;
                }

                // Mitsubishi want to choose tabpage ... 
                lbRequired = true;
                DataTable tblBCRD10 = (DataTable)Session["BCRD10Table"];
                if (tblBCRD10 != null)
                {
                    foreach (DataRow dr in tblBCRD10.Rows)
                    {
                        if (dr["Selected"].ToString().Equals("True"))
                        {
                            lbRequired = false;
                            break;
                        }
                    }
                    if (lbRequired) MessageBuilder += "Mitsubishi want to choose" + comma;
                }

                // Reason choose Mitsubishi tabpage ...
                lbRequired = true;
                DataTable tblCCRD10 = (DataTable)Session["CCRD10Table"];
                if (tblCCRD10 != null)
                {
                    foreach (DataRow dr in tblCCRD10.Rows)
                    {
                        if (dr["Selected"].ToString().Equals("True"))
                        {
                            lbRequired = false;
                            break;
                        }
                    }
                    if (lbRequired) MessageBuilder += "Reason choose Mitsubishi" + comma;
                }

                // Result tab ...
                if (string.IsNullOrEmpty(ddlCarType.SelectedValue)) MessageBuilder += lblCarType.Text + comma;
                if (string.IsNullOrEmpty(txtBankName.Text.Trim())) MessageBuilder += lblBankName.Text + comma;
                if (string.IsNullOrEmpty(txtPaymentMethod.Text.Trim())) MessageBuilder += lblPaymentMethod.Text + newLine;

                // What's kind of Insurance tabpage ...
                lbRequired = true;
                DataTable tblECRD10 = (DataTable)Session["ECRD10Table"];
                if (tblECRD10 == null)
                {
                    foreach (DataRow dr in tblECRD10.Rows)
                    {
                        if (dr["Selected"].ToString().Equals("True"))
                        {
                            lbRequired = false;
                            break;
                        }
                    }
                    if (lbRequired) MessageBuilder += "Reason choose Mitsubishi" + comma;
                }

                // What about accessories tabpage ...
                lbRequired = true;
                DataTable tblFCRD10 = (DataTable)Session["FCRD10Table"];
                if (tblFCRD10 == null)
                {
                    foreach (DataRow dr in tblECRD10.Rows)
                    {
                        if (dr["Selected"].ToString().Equals("True"))
                        {
                            lbRequired = false;
                            break;
                        }
                    }
                    if (lbRequired) MessageBuilder += "What about accessories" + newLine;                
                }

                if (MessageBuilder.Length > 0) MessageBuilder = Prefix_Msg + MessageBuilder;
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                MessageBuilder = ex.Message;
            }
            return MessageBuilder;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public string CollectData()
        {
            try
            {
                DataTable dt = new DataTable("OCRD");
                dt.Columns.Add("CardCode");
                dt.Columns.Add("CardName");
                dt.Columns.Add("Address");
                dt.Columns.Add("LicTradNum");
                dt.Columns.Add("Phone1");
                dt.Columns.Add("Phone2");
                dt.Columns.Add("CardType");
                dt.Columns.Add("GroupCode");
                dt.Columns.Add("Cellular");
                dt.Columns.Add("Fax");
                dt.Columns.Add("E_Mail");
                dt.Columns.Add("U_ContactPerson");
                dt.Columns.Add("CmpPrivate");
                dt.Columns.Add("Series");
                dt.Columns.Add("SlpCode");
                dt.Columns.Add("Free_Text");
                dt.Columns.Add("U_IDCard");
                dt.Columns.Add("U_Age");
                dt.Columns.Add("U_Gender");
                dt.Columns.Add("U_MarialStatus");
                dt.Columns.Add("U_Income");
                dt.Columns.Add("U_MembersNumber");
                dt.Columns.Add("U_MMCownedNumber");
                dt.Columns.Add("U_MMCOwnedType");
                dt.Columns.Add("U_OtherCar");
                dt.Columns.Add("U_OtherCarOwned");
                dt.Columns.Add("U_PurposePrivate");
                dt.Columns.Add("U_PurposeCompany");
                dt.Columns.Add("U_CustomerStatus");
                dt.Columns.Add("U_DealerCode");
                dt.Columns.Add("U_ProvinceCode");

                DataRow dr = dt.NewRow();
                dr["CardCode"] = hdnCustomerCode.Value;
                dr["CardName"] = txtCustomerName.Text;
                dr["Address"] = txtAddress.Text;
                dr["LicTradNum"] = txtTaxCode.Text;
                dr["Phone1"] = txtHomeTel.Text;
                dr["Phone2"] = txtOfficeTel.Text;
                
                dr["GroupCode"] = "103";
                dr["Cellular"] = txtMobiphone.Text;
                dr["Fax"] = txtFax.Text;
                dr["E_Mail"] = txtE_Mail.Text;
                dr["U_ContactPerson"] = txtCntctPrsn.Text.Trim();
                dr["CmpPrivate"] = ddlBPType.SelectedValue;
                dr["CardType"] = ddl_CustomerType.SelectedValue;
                if(ddl_CustomerType.SelectedValue.Equals("C"))
                    dr["Series"] = 58;
                else if (ddl_CustomerType.SelectedValue.Equals("L"))
                    dr["Series"] = 59;
                dr["SlpCode"] = ddlSaleMan.SelectedValue;
                dr["Free_Text"] = txtRemark.Text.Trim();

                dr["U_IDCard"] = txtIDCard.Text.Trim();
                dr["U_Age"] = txtAge.Text.Trim();
                dr["U_Gender"] = rblGender.SelectedValue;
                dr["U_MarialStatus"] = ddl_Marital.SelectedValue;
                dr["U_Income"] = txtIncome.Text.Trim();
                dr["U_MembersNumber"] = txtMembersNo.Text.Trim();
                dr["U_MMCownedNumber"] = txtMMCOwnedQty.Text.Trim();
                dr["U_MMCOwnedType"] = txtMMCOwnedName.Text.Trim();
                dr["U_OtherCar"] = txtOtherCarOwnedQty.Text.Trim();
                dr["U_OtherCarOwned"] = txtOtherCarOwnedName.Text.Trim();
                dr["U_PurposePrivate"] = txtPurposePrivate.Text.Trim();
                dr["U_PurposeCompany"] = txtPurposeCompany.Text.Trim();
                dr["U_CustomerStatus"] = ddlCustomerStatus.SelectedValue;
                dr["U_ProvinceCode"] = txtProvinceCode.Text.Trim();
                dr["U_DealerCode"] = Session[Utils.AppConstants.ID_Dealer].ToString();
                dt.Rows.Add(dr);

                //dr["U_UserID"] = User.Identity.Name;
                DocumentXML objInfo = new DocumentXML();
                DataSet ds = new DataSet("DS");
                dt.TableName = DefineTables.BIZ_PARTNER_TITLE;
                //dtHeader.TableName = TblHeaderName;
                //dtAddress.TableName = TblAddress;
                //dtContactPerson.TableName = TblContact;
                ds.Tables.Add(dt.Copy());
                //ds.Tables.Add(dtAddress.Copy());
                //ds.Tables.Add(dtContactPerson.Copy());

                return objInfo.ToXMLStringFromDS( ConvertDocType.Get2String(DocType.BUSINESS_PARTNER), ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return string.Empty;
            }
        }

        private DataSet CollectDataDetails()
        {
            DataSet ds = new DataSet("tbl_OCRD10");
            try
            {
                DataTable tblACRD10 = (DataTable)Session["ACRD10Table"];
                if (tblACRD10 == null)
                {
                    tblACRD10 = new DataTable("tbl_ACRD10");
                    tblACRD10.Columns.Add("internal_id");
                    tblACRD10.Columns.Add("Code");
                    tblACRD10.Columns.Add("Name");
                    tblACRD10.Columns.Add("CardCode");
                    tblACRD10.Columns.Add("Selected");
                }
                DataTable tblBCRD10 = (DataTable)Session["BCRD10Table"];
                if (tblBCRD10 == null)
                {
                    tblBCRD10 = new DataTable("tbl_BCRD10");
                    tblBCRD10.Columns.Add("internal_id");
                    tblBCRD10.Columns.Add("Code");
                    tblBCRD10.Columns.Add("Name");
                    tblBCRD10.Columns.Add("CardCode");
                    tblBCRD10.Columns.Add("Selected");
                }
                DataTable tblCCRD10 = (DataTable)Session["CCRD10Table"];
                if (tblCCRD10 == null)
                {
                    tblCCRD10 = new DataTable("tbl_CCRD10");
                    tblCCRD10.Columns.Add("internal_id");
                    tblCCRD10.Columns.Add("Code");
                    tblCCRD10.Columns.Add("Name");
                    tblCCRD10.Columns.Add("CardCode");
                    tblCCRD10.Columns.Add("Selected");
                }
                DataTable tblDCRD10 = (DataTable)Session["DCRD10Table"];
                if (tblDCRD10 == null || tblDCRD10.Rows.Count <= 0)
                {
                    tblDCRD10 = new DataTable("tbl_DCRD10");
                    tblDCRD10.Columns.Add("internal_id");
                    tblDCRD10.Columns.Add("CarType");
                    tblDCRD10.Columns.Add("PaymentMethod");
                    tblDCRD10.Columns.Add("BankName");
                    tblDCRD10.Columns.Add("CardCode");
                    DataRow dr = tblDCRD10.NewRow();
                    dr["CarType"] = ddlCarType.SelectedValue;
                    dr["PaymentMethod"] = txtPaymentMethod.Text.Trim();
                    dr["BankName"] = txtBankName.Text.Trim();
                    tblDCRD10.Rows.Add(dr);
                }
                else
                {
                    DataRow dr = tblDCRD10.Rows[0];
                    dr["CarType"] = ddlCarType.SelectedValue;
                    dr["PaymentMethod"] = txtPaymentMethod.Text.Trim();
                    dr["BankName"] = txtBankName.Text.Trim();
                }
                DataTable tblECRD10 = (DataTable)Session["ECRD10Table"];
                if (tblECRD10 == null)
                {
                    tblECRD10 = new DataTable("tbl_ECRD10");
                    tblECRD10.Columns.Add("internal_id");
                    tblECRD10.Columns.Add("Code");
                    tblECRD10.Columns.Add("Name");
                    tblECRD10.Columns.Add("CardCode");
                    tblECRD10.Columns.Add("Selected");
                }

                DataTable tblFCRD10 = (DataTable)Session["FCRD10Table"];
                if (tblFCRD10 == null)
                {
                    tblFCRD10 = new DataTable("tbl_FCRD10");
                    tblFCRD10.Columns.Add("internal_id");
                    tblFCRD10.Columns.Add("Code");
                    tblFCRD10.Columns.Add("Name");
                    tblFCRD10.Columns.Add("CardCode");
                    tblFCRD10.Columns.Add("Selected");
                }
                // create ds
                ds.Tables.Add(tblACRD10.Copy());
                ds.Tables.Add(tblBCRD10.Copy());
                ds.Tables.Add(tblCCRD10.Copy());
                ds.Tables.Add(tblDCRD10.Copy());
                ds.Tables.Add(tblECRD10.Copy());
                ds.Tables.Add(tblFCRD10.Copy());
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
                lblError.Visible = true;
                return null;
            }
            return ds;
        }

        protected void ddl_BPType_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetInvisibleFields(((DropDownList)sender).SelectedValue);
        }

        private void ClearScreen()
        {
            txtCustomerCode.Text = "Auto";
            txtCustomerName.Text =
            txtAddress.Text =
            txtCntctPrsn.Text =
            txtIncome.Text = 
            txtAge.Text =
            txtProvinceCode.Text = 
            txtProvinceName.Text =
            txtFax.Text =
            txtTaxCode.Text =
            txtIDCard.Text =
            txtE_Mail.Text = 
            txtMembersNo.Text =
            txtHomeTel.Text = 
            txtOfficeTel.Text = 
            txtMobiphone.Text = 
            txtMMCOwnedQty.Text =
            txtMMCOwnedName.Text =
            txtOtherCarOwnedQty.Text =
            txtOtherCarOwnedName.Text =
            txtPurposePrivate.Text = 
            txtPurposeCompany.Text =
            txtRemark.Text =
            txtPaymentMethod.Text =
            txtBankName.Text = 
            string.Empty;

            ddl_CustomerType.SelectedIndex = 
            ddlBPType.SelectedIndex =  
            ddl_CustomerType.SelectedIndex =
            ddl_Marital.SelectedIndex =
            rbnPreparingBuy.SelectedIndex =
            rblGender.SelectedIndex =
            ddlCustomerStatus.SelectedIndex =
            ddlCarType.SelectedIndex = 
            0;
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString().Equals(Utils.AppConstants.VSM) ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            LoadDetails(dbType, this.txtCustomerCode.Text.Trim(), "A");
            LoadDetails(dbType, this.txtCustomerCode.Text.Trim(), "B");
            LoadDetails(dbType, this.txtCustomerCode.Text.Trim(), "C");
            LoadDetails(dbType, this.txtCustomerCode.Text.Trim(), "D");
            LoadDetails(dbType, this.txtCustomerCode.Text.Trim(), "E");
            LoadDetails(dbType, this.txtCustomerCode.Text.Trim(), "F");
        }

        private void SetInvisibleFields(string BPType)
        {
            if (BPType.Equals("I"))
            {
                // for Private
                lblAge.Visible = 
                lblMaritalStatus.Visible = 
                lblGender.Visible = 
                ddl_Marital.Visible = 
                rblGender.Visible = 
                lblIncome.Visible = 
                txtIncome.Visible = 
                lblIDCard.Visible = 
                lblIDCardRequired.Visible = 
                txtIDCard.Visible = true;

                lblFax.Visible =
                txtFax.Visible =
                lblCompanyType.Visible = 
                ddl_CompanyType.Visible = 
                lblTaxCode.Visible = 
                txtTaxCode.Visible =
                lblTaxCodeRequired.Visible = 
                lblYoF.Visible = false;
            }
            else if (BPType.Equals("C"))
            {
                lblAge.Visible = 
                lblMaritalStatus.Visible = 
                lblGender.Visible = 
                ddl_Marital.Visible = 
                rblGender.Visible = 
                lblIncome.Visible = 
                txtIncome.Visible = 
                lblIDCard.Visible = 
                lblIDCardRequired.Visible = 
                txtIDCard.Visible = false;
                // for Company
                lblYoF.Visible = 
                lblCompanyType.Visible = 
                ddl_CompanyType.Visible = 
                lblFax.Visible =
                txtFax.Visible =
                lblTaxCode.Visible =
                txtTaxCode.Visible =
                lblTaxCodeRequired.Visible = true;
            }        
        }

        protected void chkASelection_CheckedChanged(object sender, EventArgs e)
        {
            DataTable tblACRD10 = (DataTable)Session["ACRD10Table"];
            GridViewRow row = (GridViewRow)((DataControlFieldCell)((CheckBox)sender).Parent).Parent;
            Label lblNo = (Label)row.FindControl("lblNo");
            if (tblACRD10 != null)
            {
                DataRow[] rupdate = tblACRD10.Select("No=" + lblNo.Text);
                if (rupdate.Length > 0) rupdate[0]["Selected"] = ((CheckBox)row.FindControl("chkASelection")).Checked;
                BindDataDetails(tblACRD10, "A");
            }
        }

        protected void chkBSelection_CheckedChanged(object sender, EventArgs e)
        {
            DataTable tblBCRD10 = (DataTable)Session["BCRD10Table"];
            GridViewRow row = (GridViewRow)((DataControlFieldCell)((CheckBox)sender).Parent).Parent;
            Label lblNo = (Label)row.FindControl("lblNo");
            if (tblBCRD10 != null)
            {
                DataRow[] rupdate = tblBCRD10.Select("No=" + lblNo.Text);
                if (rupdate.Length > 0) rupdate[0]["Selected"] = ((CheckBox)row.FindControl("chkBSelection")).Checked;
                BindDataDetails(tblBCRD10, "B");
            }
        }

        protected void chkCSelection_CheckedChanged(object sender, EventArgs e)
        {
            DataTable tblCCRD10 = (DataTable)Session["CCRD10Table"];
            GridViewRow row = (GridViewRow)((DataControlFieldCell)((CheckBox)sender).Parent).Parent;
            Label lblNo = (Label)row.FindControl("lblNo");
            if (tblCCRD10 != null)
            {
                DataRow[] rupdate = tblCCRD10.Select("No=" + lblNo.Text);
                if (rupdate.Length > 0) rupdate[0]["Selected"] = ((CheckBox)row.FindControl("chkCSelection")).Checked;
                BindDataDetails(tblCCRD10, "C");
            }
        }

        protected void chkESelection_CheckedChanged(object sender, EventArgs e)
        {
            DataTable tblECRD10 = (DataTable)Session["ECRD10Table"];
            GridViewRow row = (GridViewRow)((DataControlFieldCell)((CheckBox)sender).Parent).Parent;
            Label lblNo = (Label)row.FindControl("lblNo");
            if (tblECRD10 != null)
            {
                DataRow[] rupdate = tblECRD10.Select("No=" + lblNo.Text);
                if (rupdate.Length > 0) rupdate[0]["Selected"] = ((CheckBox)row.FindControl("chkESelection")).Checked;
                BindDataDetails(tblECRD10, "E");
            }
        }

        protected void chkFSelection_CheckedChanged(object sender, EventArgs e)
        {
            DataTable tblFCRD10 = (DataTable)Session["FCRD10Table"];
            GridViewRow row = (GridViewRow)((DataControlFieldCell)((CheckBox)sender).Parent).Parent;
            Label lblNo = (Label)row.FindControl("lblNo");
            if (tblFCRD10 != null)
            {
                DataRow[] rupdate = tblFCRD10.Select("No=" + lblNo.Text);
                if (rupdate.Length > 0) rupdate[0]["Selected"] = ((CheckBox)row.FindControl("chkFSelection")).Checked;
                BindDataDetails(tblFCRD10, "F");
            }
        }

        protected void txtIDCard_TextChanged(object sender, EventArgs e)
        {
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = (GeneralFunctions)Session["GeneralFunctions"];
            string lsIDCard = ((TextBox)sender).Text.Trim();
            if (string.IsNullOrEmpty(lsIDCard)) return;
            string sqlCommand = string.Empty;

            if (string.IsNullOrEmpty(txtCustomerCode.Text.Trim()) || txtCustomerCode.Text.Trim().CompareTo("Auto.") == 0) // new customer
                sqlCommand = "select count(U_IDCard) rc from OCRD where U_IDCard = '" + lsIDCard + "'";
            else // update customer
                sqlCommand = "select count(U_IDCard) rc from OCRD where CardCode <> '" + txtCustomerCode.Text.Trim() + "' and U_IDCard = '" + lsIDCard + "'";
            string lsRC = GF.GetSingleValue(dbType, sqlCommand, "rc");
            if (!string.IsNullOrEmpty(lsRC) && lsRC.CompareTo("0") != 0)
            {
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Invalid ID. Card. Pls input another ID. Card.');", true);
                txtTaxCode.Focus();
                return;
            }
        }

        protected void txtTaxCode_TextChanged(object sender, EventArgs e)
        {
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = (GeneralFunctions)Session["GeneralFunctions"];
            string lsTaxCode = ((TextBox)sender).Text.Trim();
            if (string.IsNullOrEmpty(lsTaxCode)) return;

            string sqlCommand = string.Empty;
            if (string.IsNullOrEmpty(txtCustomerCode.Text.Trim()) || txtCustomerCode.Text.Trim().CompareTo("Auto.") == 0) // new customer
                sqlCommand = "select count(LicTradNum) rc from OCRD where LicTradNum = '" + lsTaxCode + "'";
            else // update customer
                sqlCommand = "select count(LicTradNum) rc from OCRD where CardCode <> '" + txtCustomerCode.Text.Trim() + "' and LicTradNum = '" + lsTaxCode + "'";
            string lsRC = GF.GetSingleValue(dbType, sqlCommand, "rc");
            if (!string.IsNullOrEmpty(lsRC) && lsRC.CompareTo("0") != 0)
            {
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Invalid Tax Code. Pls input another Tax Code.');", true);
                txtTaxCode.Focus();
                return;
            }
        }

        protected void ddl_CustomerType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddl_CustomerType.SelectedValue.Equals("L") )
                lblNotification.Visible = false; //to hide
            else
                lblNotification.Visible = true; //to show
        }
    }
}